package com.futvan.z.framework.core;

import java.util.HashMap;
import java.util.Map;

import javax.servlet.http.HttpSession;

import org.springframework.http.server.ServerHttpRequest;
import org.springframework.http.server.ServerHttpResponse;
import org.springframework.http.server.ServletServerHttpRequest;
import org.springframework.web.socket.WebSocketHandler;
import org.springframework.web.socket.server.support.HttpSessionHandshakeInterceptor;

import com.futvan.z.system.zuser.z_user;

public class WebSocketInterceptor extends HttpSessionHandshakeInterceptor {

	/**
	 * ServletServerHttpRequest 中信息转 WebSocketSession 中
	 */
	@Override
	public boolean beforeHandshake(ServerHttpRequest request, ServerHttpResponse response, WebSocketHandler wsHandler,Map<String, Object> attributes) throws Exception {
		if (request instanceof ServletServerHttpRequest) {
			//实例化参数集合
			if(z.isNull(attributes)) {
        		attributes = new HashMap<String, Object>();
        	}
			//判读request是否是ServletServerHttpRequest
			ServletServerHttpRequest servletRequest = (ServletServerHttpRequest) request;
			HttpSession session = servletRequest.getServletRequest().getSession(false);
			//如果session不为空，并且session中有登录用户信息
            if (session!=null && z.isNotNull(session.getAttribute("zuser"))) {
            	//将用户信息转存到WebSocket中
            	attributes.put("zuser", session.getAttribute("zuser"));
            	attributes.put("zorg", session.getAttribute("zorg"));
            	attributes.put("sp", session.getAttribute("sp")); 
            }else {
            	//APP连接websocket
            	String zuserid = servletRequest.getServletRequest().getParameter("zuser");
            	if(z.isNotNull(zuserid) && z.isNotNull(z.users.get(zuserid))) {
            		z_user zuser = z.users.get(zuserid);
            		attributes.put("zuser", zuser);
            	}
            }
		}
		return super.beforeHandshake(request, response, wsHandler, attributes);
	}


}
